<script setup lang="ts">
import {nextTick, reactive, ref, useAttrs} from "vue";
import {type FormInterface} from "./formType";
import type {FormInstance} from "element-plus";
const dialogVisible = ref(false)
const ruleFormRef = ref<FormInstance>()
const rules = {
  name: [
    {required: true, message: '请输入姓名', trigger: 'blur'},
    {min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur'}
  ],
  address: [
    {required: true, message: '请输入地址', trigger: 'blur'}
  ]
}
const props = defineProps({
  api : {
    type: Object,
    required: true
  }
})
const form = reactive<FormInterface>({
  id: '',
  name: '',
  address: ''
})
const openDialog = (row?: FormInterface) => {
  dialogVisible.value = true
  Object.assign(form, {
    id : row?.id || '',
    name : row?.name || '',
    address : row?.address || '',
  })
}
const submit = async () => {
   ruleFormRef.value?.validate((valid, fields) => {
    if (valid) {
      let res = form.id === '' ?  props.api.create(form) :  props.api.update(form)
      console.log(res)
    } else {
      console.log('error submit!', fields)
    }
  })

}




defineExpose({openDialog})
</script>

<template>
  <el-dialog
      v-model="dialogVisible"
      :title="form.id === '' ? '新增' : '编辑'"
      width="30%"
  >
  <el-form :model="form" label-width="80px"  :rules="rules" ref="ruleFormRef">
    <el-form-item label="姓名" prop="name">
      <el-input v-model="form.name"  />
    </el-form-item>
    <el-form-item label="地址" prop="address">
      <el-input v-model="form.address" />
    </el-form-item>
  </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submit"
        >提交</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>

</style>